home *** CD-ROM | disk | FTP | other *** search
- Message-ID: <31517CF6.7C6F@novell.com>
- Date: Thu, 21 Mar 1996 08:59:50 -0700
- From: Sukanta Ganguly <sukanta_ganguly@novell.com>
- Organization: Novell Inc
- X-Mailer: Mozilla 2.0 (WinNT; I)
- MIME-Version: 1.0
- Newsgroups: comp.lang.c++
- Subject: Re: object creation from an abstract base class
- References: <4hj285$c87@comet.magicnet.net>
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- NNTP-Posting-Host: sganguly.npd.provo.novell.com
- Path: news.provo.novell.com!
-
- Michael Catello wrote:
- >
- > Hello OOPsters,
- >
- > I was just looking for validation/other suggestions for a method I
- > recently used in a program. I have defined an abstract base class
- > (i.e. contains pure virtual functions), all access to the derived
- > classes of this base are thru a pointer to the base class. To create
- > the actual objects of the derived classes I used the following scheme:
- >
- > enum FooType {BAR, BAS};
- >
- > // base class
- > class CFoo
- > {
- > CFoo();
- > ~CFoo();
- >
- > static CFoo* CreateFoo(FooType type);
- >
- > // other methods/data including pure virtual fns whose behaviour will
- > be defined in the derived classes
- > };
- >
- > class CBar: public CFoo
- > {
- > //
- > };
- >
- > class CBas: public CFoo
- > {
- > //
- > };
- >
- > CFoo* CFoo::CreateFoo(FooType type)
- > {
- > CFoo* pfoo = NULL;
- >
- > switch (type)
- > {
- > case BAR:
- > pfoo = new CBar;
- > break;
- > case BAS:
- > pfoo = new CBas;
- > break;
- > }
- >
- > return pfoo;
- > }
- >
- > main()
- > {
- > CFoo* interface = CFoo::CreateFoo(BAR);
- > }
- >
- > Obviously it is the CreateFoo() function that I am wondering about. In
- > the actual implementation I had multiple static "Create" functions for
- > the base class that would allow me to create a new object: one based
- > on an enumerated token (shown above), another an existing object, as
- > well as one based on the format of a datafile. My application never
- > references any of the derived classes directly, except in their
- > creation and definition.
- >
- > Is there another/better/more appropriate way to handle this type of
- > object creation? Thanks for your assistance,
- >
- > Regards,
- > -Michael.
- >
- > /*
- > * catello@magicnet.net
- > * http://www.magicnet.net/~catello
- > * CompuServe: 70401,3661
- > */Hi,
- I looked at your code snippet and was slightly confused. In your
- CreateFoo method of CFoo class, the pfoo variable is a pointer
- to CFoo which has no idea of what are CBas or CBar. But in your
- code you are creating CBas as well as CBar objects and storing
- it in pfoo. In your derived CBar and CBas you would obviously
- have more data members which CFoo* would not be addressing. The
- compiler should crib at you at places like "pfoo = new CBas"
- and "pfoo = new CBar". I wouldn't do it like this.
-
- Thanx
-